package com.ruoyi.framework.interceptor;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.constant.ReportConstants;
import com.ruoyi.common.core.domain.entity.RepUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.AuthorizationException;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * @author cpf
 * @date 2024/1/29 11:28
 * @description 前端页面拦截器
 */
@Component
public class ReportInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisCache redisCache;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求头中获取token
        String header = request.getHeader(ReportConstants.AUTHORIZATION_HEADER);
        //校验token
        if (!validateToken(header)) {
            throw new AuthorizationException("用户未登录，请登录！");
        }
        //截取token
        String token = header.substring(7);
        //从redis中查询登录对象
        String jsonUser = redisCache.getCacheObject(ReportConstants.REP_USER_TOKEN + token);
        RepUser user = JSON.parseObject(jsonUser, RepUser.class);
        if (user == null) {
            throw new AuthorizationException("用户未登录，请登录！");
        }
        //token续期
        redisCache.expire(ReportConstants.REP_USER_TOKEN + token, 15, TimeUnit.DAYS);
        //把用户信息存放到ThreadLocalUtils中
        ThreadLocalUtils.userThreadLocal.set(user);
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //移除当前线程的用户信息
        ThreadLocalUtils.userThreadLocal.remove();
    }

    /**
     * 验证Token是否有效的方法，这里仅作为示例，实际应用中需要对接具体的认证服务或数据库进行验证
     *
     * @param token 用户提供的Token
     * @return 如果Token有效则返回true，否则返回false
     */
    private boolean validateToken(String token) {
        // 实际业务逻辑，例如查询数据库或者调用JWT解码服务
        // 这里仅为示例，直接返回true
        // 在真实场景下，你需要替换为实际的token验证逻辑
        return !StringUtils.isEmpty(token) && token.startsWith("Bearer ");
    }
}
